package top.saplf.library.ext

import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty

/**
 * @author saplf
 */
private class VarLazy<T>(
        private var initializer: () -> T,
        private var setter: ((T) -> Unit)?
) : ReadWriteProperty<Any?, T> {

    private var value: T? = null

    override fun getValue(thisRef: Any?, property: KProperty<*>): T {
        return value ?: initializer()
    }

    override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
        this.value = value
        setter?.invoke(value)
    }
}

fun <T> varLazy(initializer: () -> T, setter: ((T) -> Unit)? = null)
        : ReadWriteProperty<Any?, T> = VarLazy(initializer, setter)
